<?php

namespace App\Http\Controllers\Api;

use App\Domain\BooksInDoor\Model\BooksInDoor;
use App\Domain\BooksInDoor\Service\BooksInDoorService;
use App\Domain\Door\Service\DoorService;
use App\Domain\ErrBook\Model\ErrBook;
use App\Domain\ErrBook\Service\ErrBookService;
use App\Domain\ErrBookLog\Service\ErrBookLogService;
use App\Domain\Item\Service\ItemService;
use App\Domain\Lendhist\Model\Lendhist;
use App\Domain\Lendhist\Service\LendhistService;
use App\Domain\Lendlist\Service\LendlistService;
use App\Domain\Reader\Service\ReaderService;
use App\Domain\TagInfo\Service\TagInfoService;
use App\Exceptions\ApiException;
use App\Util\Result;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Validator;

class BookController extends Controller
{
    protected $tagInfoService = null;
    protected $doorService = null;
    protected $readerService = null;
    protected $lendHisService = null;
    protected $lendLisService = null;
    protected $itemService = null;
    protected $errBookService = null;
    protected $errBookLogService = null;
    protected $bookInDoorService = null;


    public function __construct(Request $request, TagInfoService $tagInfoService, DoorService $doorService,ReaderService $readerService,LendhistService $lendHisService,LendlistService $lendlistService,ItemService $itemService ,ErrBookService $errBookService , ErrBookLogService $errBookLogService,BooksInDoorService $booksInDoorService)
    {
        $this->request = $request;
        $this->tagInfoService = $tagInfoService;
        $this->doorService = $doorService;
        $this->readerService = $readerService;
        $this->lendHisService = $lendHisService;
        $this->lendLisService = $lendlistService;
        $this->itemService = $itemService;
        $this->errBookService = $errBookService;
        $this->errBookLogService = $errBookLogService;
        $this->bookInDoorService = $booksInDoorService;

    }

    /**
     * @return $this
     * 扫码使用
     * czs
     */
    public function sendContent()
    {
        $content = $this->request->input('content');
        $data['uid'] = $this->request->input('uid');
        $data['number'] = substr($content, 0, 6);
        $data['code'] = substr($content, 6, 6);
        $data['column'] = substr($content, 12);
        $data['time'] = time();

        $reader=$this->readerService->getReaderByUid( $data['uid']);
        if(!$reader){
            return Result::failure()->setType(1)->getResult();
        }

        //查找门的状态
        $door=DB::table('doors')->where('code',$data['code'])
            ->first();

        if(!$door){
            return Result::failure()->setType(1)->getResult();
        }

        //门是开着的状态返回错误
        if($door->status==2){
            return Result::failure()->setType(1)->getResult();
        }

        //读者
        if(!$reader->is_main){
            //判断有没有其他门开着
            $open=DB::table('reader_door')->where('readerId',$data['uid'])
                ->first();
            if($open){
                return Result::failure()->setType(1)->getResult();
            }
            $result=DB::table('reader_door')->insert(
                [
                    'readerId' => $data['uid'],
                    'code'     => $data['code'],
                    'time'     => $data['time']
                ]
            );
            if(!$result){
                return Result::failure()->setType(1)->getResult();
            }
        }

        //查找状态
        $sel = DB::table('temp_table')->where('code',$data['code']);

        if ($sel->count() > 0) {
            $sel->delete();
        }

        $res = DB::table('temp_table')->insert($data);

        if ($res) {
            return Result::success()->setType(0)->getResult();
        } else {
            return Result::failure()->setType(1)->getResult();
        }
    }




    /**
     * 开门成功返回
     */
    public function delContent()
    {
        $code = $this->request->input('code');
        $res = DB::table('doors')->where('code', $code)
            ->update(['status' => 2]);
        if ($res) {
            return Result::success()->setType(0)->getResult();
        } else {
            return Result::failure()->setType(1)->getResult();
        }
    }

    /**
     * 关门请求返回
     */
    public function close()
    {
        $code = $this->request->input('code');
        $res = DB::table('doors')->where('code', $code)
            ->update(['status' => 1]);
        if(!$res){
            return Result::failure()->setType(1)->getResult();
        }
        //删除读者关系
        $result=DB::table('reader_door')->where('code',$code)->delete();
        if ($result) {
            return Result::success()->setType(0)->getResult();
        } else {
            return Result::failure()->setType(1)->getResult();
        }

    }

    /**
     *超时未关门
     */
    public function dueClose()
    {
        $uid = $this->request->input('uid');
        $code = $this->request->input('code');
        $number = DB::table('doors as a')->where('a.code', $code)
            ->leftjoin('shelves as b', 'b.id', '=', 'a.sid');
        if ($number->count() > 0) {
            $datas['uid'] = $uid;
            $datas['cabinet'] = $number->value('b.number');
            $url = "https://api.lexiangyueshu.com/callback/warning";
            $ci = curl_init();
            curl_setopt($ci, CURLOPT_TIMEOUT, 30);
            curl_setopt($ci, CURLOPT_RETURNTRANSFER, true);
            $params = http_build_query($datas);
            if (!empty($params)) {
                curl_setopt($ci, CURLOPT_POST, true);
                curl_setopt($ci, CURLOPT_POSTFIELDS, $params);
            }
            curl_setopt($ci, CURLOPT_SSL_VERIFYPEER, false);
            curl_setopt($ci, CURLOPT_SSL_VERIFYHOST, false);
            curl_setopt($ci, CURLOPT_URL, $url);
            curl_exec($ci);
            curl_close($ci);
            return Result::success()->setType(0)->getResult();
        } else {
            return Result::failure()->setType(1)->getResult();
        }
    }

    /**
     * 还书箱还书
     */
    public function backBookBox(Request $request)
    {
        $post = $request->all();
        if ($this->boxBookValidator($post)->fails()) {
            return Result::failure()->setType(1)->setMsg(ApiException::VALIDATE_INPUT_FAIL)->getResult();
        }

        //高频标签id数组
        $rfid = explode(",", $post['rfid']);
        $rfid = is_array($rfid)?$rfid:[];
        //还书箱码
        $code = $post['number'];

        $m='';

        //还书箱还书
        foreach ($rfid as $k => $v) {
            //判断书籍
            $tag = $this->tagInfoService->getTagStatusByRfid($v);
            //不存在的书
            if (!$tag || $tag->Barcode == null) {
                $result = $this->errorBookWork($v, $code, '', ErrBook::STATUS_1, '还书箱放入空标签');
                if (!$result) {
                    $m .= '空标签rfid:' . $v . ApiException::ERRBOOK_WORK_FAIL;
                }
                continue;
            }

            $item = $this->itemService->getItemByBarCode($tag->Barcode);
            //不存在的书
            if (!$item ) {
                $result = $this->errorBookWork($v, $code, '', ErrBook::STATUS_1, '还书箱放入空标签');
                if (!$result) {
                    $m .= '空标签rfid:' . $v . ApiException::ERRBOOK_WORK_FAIL;
                }
                continue;
            }
            //更新书机器关系


            //异常书 b_status=1
            if ($item->bookstatus) {
                $result = $this->errorBookWork($v, $code, '', ErrBook::STATUS_1, '还书箱放入异常书籍');
                if (!$result) {
                    $m .= '异常书籍rfid:' . $v . ApiException::ERRBOOK_WORK_FAIL;
                }
                continue;
            }

            switch ($item->LTStatus) {
                case '1':
                    //更新为异常书 1
                    $result = $item->update(['bookstatus' => 1]);
                    if (!$result) {
                        $m .= 'rfid:' . $v . ApiException::UPDATE_BOOK_YC_FAIL;
                    }
                    $result = $this->errorBookWork($v, $code, '', ErrBook::STATUS_1, '还书箱放入仓库书籍');
                    if (!$result) {
                        $m .= '仓库书籍rfid:' . $v . ApiException::ERRBOOK_WORK_FAIL;
                    }
                    break;
                case '2':
                    break;
                case '3':
                    //更新为待上架状态  2
                    $result = $item->update(['LTStatus' => 2]);
                    if (!$result) {
                        $m .= 'rfid:' . $v . ApiException::FOR_UPDATE_BOOK_SJ_FAIL;
                    }
                    break;
                case '4':
                    //还书操作
                    $result = $this->returnBook($item->SerialNo,$code,$code);
                    if (!$result) {
                        $m .= 'rfid:' . $v . ApiException::BACK_BOOK_FAIL;
                    }
                    //更新为待上架状态  2
                    $result = $item->update(['LTStatus' => 2]);
                    if (!$result) {
                        $m .= 'rfid:' . $v . ApiException::FOR_UPDATE_BOOK_SJ_FAIL;
                    }
                    break;
                case '5':
                    //更新为待上架状态  2
                    $result = $item->update(['LTStatus' => 2]);
                    if (!$result) {
                        $m .= 'rfid:' . $v . ApiException::FOR_UPDATE_BOOK_SJ_FAIL;
                    }
                    break;
                case '6':
                    //更新为异常书 1
                    $result = $item->update(['bookstatus' => 1]);
                    if (!$result) {
                        $m .= 'rfid:' . $v . ApiException::UPDATE_BOOK_YC_FAIL;
                    }
                    $result = $this->errorBookWork($v, $code, '', ErrBook::STATUS_1, '还书箱放入外售书籍');
                    if (!$result) {
                        $m .= '外售书籍rfid:' . $v . ApiException::ERRBOOK_WORK_FAIL;
                    }
                    break;
                default:
                    //更新为异常书 1
                    $result = $item->update(['bookstatus' => 1]);
                    if (!$result) {
                        $m .= 'rfid:' . $v . ApiException::UPDATE_BOOK_YC_FAIL;
                    }
                    $result = $this->errorBookWork($v, $code, '', ErrBook::STATUS_1, '还书箱放入未知状态书籍');
                    if (!$result) {
                        $m .= '未知状态书籍rfid:' . $v . ApiException::ERRBOOK_WORK_FAIL;
                    }
                    break;
            }

        }

        if (empty($m)) {
            return Result::success()->setType(0)->getResult();
        } else {
            return Result::failure()->setType(1)->setMsg($m)->getResult();
        }
    }

    //还书箱参数验证
    protected function boxBookValidator(array $data)
    {
        return Validator::make($data, [
            'rfid' => 'required|string',
            'number' => 'required|string|max:255',
        ]);
    }

    /**
     * 还书箱状态
     */
    public function bookBoxStatus()
    {
        $number = $this->request->input('number');
        $data['status'] = $this->request->input('status');
        $data['remark'] = $this->request->input('remark');
        $res = DB::table('shelves')->where('number', $number)->update($data);
        if ($res) {
            return Result::success()->setType(0)->getResult();
        } else {
            return Result::failure()->setType(1)->getResult();
        }
    }



    public function openDoor()
    {
        $number = $this->request->input('number');
        $sel = DB::table('temp_table')->where('number', $number)->orderby('id')->limit(1);
        if ($sel->count() == 0) {
             return Result::failure()->setType(1)->getResult();
        }
        $time = time() - $sel->value('time');
        if ($time > 30) {
            $del = $sel->delete();
            if ($del) {
                 return Result::failure()->setType(1)->getResult();
            }
        }
        $sel2 = DB::table('temp_table')->where('number', $number)->orderby('id')->limit(1)->select('code', 'uid', 'column')->first();
        $sel->delete();
        if ($sel2) {
              return Result::success()->setType(0)->setData($sel2)->getResult();
        }
    }




    //借书
    public function addMemberBook(Request $request){
        $post = $request->all();
        if ($this->lendBookValidator($post)->fails()) {
            return Result::failure()->setType(1)->setMsg(ApiException::VALIDATE_INPUT_FAIL)->getResult();
        }

        //高频标签id数组
        $rfid = explode(",", $post['rfid']);
        $rfid = is_array($rfid)?$rfid:[];
        //门码id
        $code = $post['number'];

        $number =  DB::table('doors as a')->where('a.code',$code)
            ->leftjoin('shelves as b','b.id','=','a.sid')
            ->value('b.number');

        //用户id
        $uid = $post['uid'];
        //判断当前用户角色
        $reader=$this->readerService->getReaderByUid($uid);

        if(!$reader){
            return Result::failure()->setType(1)->setMsg(ApiException::USER_NOT_FIND)->getResult();
        }

        if (empty($reader->is_main)) {
            //读者
            $m=$this->lendBookByReader($rfid,$uid,$code,$number);
        } else {
            //管理员
            $m=$this->lendBookByAdmin($rfid,$uid,$code,$number);
        }
        if (empty($m)) {
            return Result::success()->setType(0)->getResult();
        } else {
            return Result::failure()->setType(1)->setMsg($m)->getResult();
        }

    }

    //还书参数验证
    protected function lendBookValidator(array $data)
    {
        return Validator::make($data, [
            'uid' => 'required|string|max:255',
            'rfid' => 'required|string',
            'number' => 'required|string|max:255',
        ]);
    }


    /**
     * 还书
     */
    public function backBook(Request $request)
    {
        $post = $request->all();
        if ($this->BackBookValidator($post)->fails()) {
            return Result::failure()->setType(1)->setMsg(ApiException::VALIDATE_INPUT_FAIL)->getResult();
        }

        //高频标签id数组
        $rfid = explode(",", $post['rfid']);
        $rfid = is_array($rfid)?$rfid:[];
        //门码id
        $code = $post['code'];

        $number =  DB::table('doors as a')->where('a.code',$code)
            ->leftjoin('shelves as b','b.id','=','a.sid')
            ->value('b.number');

        //用户id
        $uid = $post['uid'];
        //判断当前用户角色
        $reader=$this->readerService->getReaderByUid($uid);
        if(!$reader){
            return Result::failure()->setType(1)->setMsg(ApiException::USER_NOT_FIND)->getResult();
        }
        if (empty($reader->is_main)) {
            //读者
            $m=$this->returnBookByReader($rfid,$uid,$code,$number);
        } else {
            //管理员
            $m=$this->returnBookByAdmin($rfid,$uid,$code,$number);
        }
        if (empty($m)) {
            return Result::success()->setType(0)->getResult();
        } else {
            return Result::failure()->setType(1)->setMsg($m)->getResult();
        }
    }

    //还书参数验证
    protected function BackBookValidator(array $data)
    {
        return Validator::make($data, [
            'uid' => 'required|string|max:255',
            'rfid' => 'required|string',
            'code' => 'required|string|max:255',
        ]);
    }

     /**读者借书
     * @param $rfid
     * @param $uid
     * @param $code     //门码
     * @param $number   //门内书的数量
     */
    public function  lendBookByReader($rfid,$uid,$code,$number){
        $m='';
        //用户
        foreach ($rfid as $k => $v) {
            //判断书籍
            $tag = $this->tagInfoService->getTagStatusByRfid($v);
            //不存在的书
            if (!$tag || $tag->Barcode == null) {
                $result = $this->errorBookWork($v, $code, $uid, ErrBook::STATUS_1, '读者拿走空标签');
                if (!$result) {
                    $m .= '空标签rfid:' . $v . ApiException::ERRBOOK_WORK_FAIL;
                }
                continue;
            }
            $item = $this->itemService->getItemByBarCode($tag->Barcode);

            //不存在的书
            if (!$item ) {
                $result = $this->errorBookWork($v, $code, $uid, ErrBook::STATUS_1, '读者拿走空标签');
                if (!$result) {
                    $m .= '空标签rfid:' . $v . ApiException::ERRBOOK_WORK_FAIL;
                }
                continue;
            }

            //更新书机器关系
            $result=$this->bookInDoorService->lendUpdateRelation($code,$v);
            if(!$result){
                $m .= 'rfid:' . $v . ApiException::UPDATE_BOOK_IN_DOOR_FAIL;
            }

            //异常书 b_status=1
            if ($item->bookstatus) {
                $result = $this->errorBookWork($v, $code, $uid, ErrBook::STATUS_1, '读者拿走异常书籍');
                if (!$result) {
                    $m .= '异常书籍rfid:' . $v . ApiException::ERRBOOK_WORK_FAIL;
                }
                continue;
            }

            switch ($item->LTStatus) {
                case '1':
                    //更新为异常书 1
                    $result = $item->update(['bookstatus' => 1]);
                    if (!$result) {
                        $m .= 'rfid:' . $v . ApiException::UPDATE_BOOK_YC_FAIL;
                    }
                    $result = $this->errorBookWork($v, $code, $uid, ErrBook::STATUS_1, '读者拿走仓库书籍');
                    if (!$result) {
                        $m .= '仓库书籍rfid:' . $v . ApiException::ERRBOOK_WORK_FAIL;
                    }
                    break;
                case '2':
                    //更新为上架状态  3
                    $result = $item->update(['LTStatus' => 3]);
                    if (!$result) {
                        $m .= 'rfid:' . $v . ApiException::UPDATE_BOOK_SJ_FAIL;
                    }
                    //借书操作
                    $result = $this->borrowBook($item->SerialNo, $code,$uid,$number);
                    if (!$result) {
                        $m .= 'rfid:' . $v . ApiException::LEND_BOOK_FAIL;
                    }
                    break;
                case '3':
                    //借书操作
                    $result = $this->borrowBook($item->SerialNo, $code,$uid,$number);
                    if (!$result) {
                        $m .= 'rfid:' . $v . ApiException::LEND_BOOK_FAIL;
                    }
                    break;
                case '4':
                    //还书操作
                    $result = $this->returnBook($item->SerialNo, $code,$number);
                    if (!$result) {
                        $m .= 'rfid:' . $v . ApiException::BACK_BOOK_FAIL;
                    }
                    //更新为上架状态  3
                    $result = $item->update(['LTStatus' => 3]);
                    if (!$result) {
                        $m .= 'rfid:' . $v . ApiException::UPDATE_BOOK_SJ_FAIL;
                    }
                    //借书操作
                    $result = $this->borrowBook($item->SerialNo, $code,$uid,$number);
                    if (!$result) {
                        $m .= 'rfid:' . $v . ApiException::LEND_BOOK_FAIL;
                    }
                    break;
                case '5':
                    //更新为上架状态  3
                    $result = $item->update(['LTStatus' => 3]);
                    if (!$result) {
                        $m .= 'rfid:' . $v . ApiException::UPDATE_BOOK_SJ_FAIL;
                    }
                    //借书操作
                    $result = $this->borrowBook($item->SerialNo, $code,$uid,$number);
                    if (!$result) {
                        $m .= 'rfid:' . $v . ApiException::LEND_BOOK_FAIL;
                    }
                    break;
                case '6':
                    //更新为异常书 1
                    $result = $item->update(['bookstatus' => 1]);
                    if (!$result) {
                        $m .= 'rfid:' . $v . ApiException::UPDATE_BOOK_YC_FAIL;
                    }
                    $result = $this->errorBookWork($v, $code, $uid, ErrBook::STATUS_1, '读者拿走外售书籍');
                    if (!$result) {
                        $m .= '外售书籍rfid:' . $v . ApiException::ERRBOOK_WORK_FAIL;
                    }
                    break;
                default:
                    //更新为异常书 1
                    $result = $item->update(['bookstatus' => 1]);
                    if (!$result) {
                        $m .= 'rfid:' . $v . ApiException::UPDATE_BOOK_YC_FAIL;
                    }
                    $result = $this->errorBookWork($v, $code, $uid, ErrBook::STATUS_1, '读者拿走未知状态书籍');
                    if (!$result) {
                        $m .= '未知状态书籍rfid:' . $v . ApiException::ERRBOOK_WORK_FAIL;
                    }
                    break;
            }

        }

        return $m;
    }


    /*管理员拿走图书
    * @param $rfid
    * @param $uid
    * @param $code     //门码
    */
    public function  lendBookByAdmin($rfid,$uid,$code,$number){
        $m='';
        //管理员
        foreach ($rfid as $k => $v) {
            //判断书籍
            $tag = $this->tagInfoService->getTagStatusByRfid($v);
            //不存在的书
            if (!$tag || $tag->Barcode == null) {
                $result = $this->errorBookWork($v, $code, $uid, ErrBook::STATUS_1, '管理员拿走空标签');
                if (!$result) {
                    $m .= '空标签rfid:' . $v . ApiException::ERRBOOK_WORK_FAIL;
                }
                continue;
            }

            $item = $this->itemService->getItemByBarCode($tag->Barcode);

            //不存在的书
            if (!$item) {
                $result = $this->errorBookWork($v, $code, $uid, ErrBook::STATUS_1, '管理员拿走空标签');
                if (!$result) {
                    $m .= '空标签rfid:' . $v . ApiException::ERRBOOK_WORK_FAIL;
                }
                continue;
            }

            if($item->LTStatus != '3'){
                //更新书机器关系
                $result=$this->bookInDoorService->lendUpdateRelation($code,$v);
                if(!$result){
                    $m .= 'rfid:' . $v . ApiException::UPDATE_BOOK_IN_DOOR_FAIL;
                }
            }

            //异常书 b_status=1
            if ($item->bookstatus) {
                $result = $this->errorBookWork($v, $code, $uid, ErrBook::STATUS_1, '管理员拿走异常书籍');
                if (!$result) {
                    $m .= '异常书籍rfid:' . $v . ApiException::ERRBOOK_WORK_FAIL;
                }
                continue;
            }

            switch ($item->LTStatus) {
                case '1':
                    break;
                case '2':
                    break;
                case '3':
                    //特殊情况处理
                    $book=BooksInDoor::where('BookEpc',$v)->first();
                    if ($book->DoorID == $code) {
                        //更新书机器关系
                        $result = $this->bookInDoorService->lendUpdateRelation($code, $v);
                        if (!$result) {
                            $m .= 'rfid:' . $v . ApiException::UPDATE_BOOK_IN_DOOR_FAIL;
                        }
                        //更新为待上架状态  2
                        $result = $item->update(['LTStatus' => 2]);
                        if (!$result) {
                            $m .= 'rfid:' . $v . ApiException::UPDATE_BOOK_SJ_FAIL;
                        }
                    }
                    break;
                case '4':
                    //还书操作
                    $result = $this->returnBook($item->SerialNo, $code,$number);
                    if (!$result) {
                        $m .= 'rfid:' . $v . ApiException::BACK_BOOK_FAIL;
                    }

                    //更新为上架状态  2
                    $result = $item->update(['LTStatus' => 2]);
                    if (!$result) {
                        $m .= 'rfid:' . $v . ApiException::UPDATE_BOOK_SJ_FAIL;
                    }
                    break;
                case '5':
                    break;
                case '6':
                    //更新为异常书 1
                    $result = $item->update(['bookstatus' => 1]);
                    if (!$result) {
                        $m .= 'rfid:' . $v . ApiException::UPDATE_BOOK_YC_FAIL;
                    }
                    $result = $this->errorBookWork($v, $code, $uid, ErrBook::STATUS_1, '管理员拿走外售书籍');
                    if (!$result) {
                        $m .= '外售书籍rfid:' . $v . ApiException::ERRBOOK_WORK_FAIL;
                    }
                    break;
                default:
                    //更新为异常书 1
                    $result = $item->update(['bookstatus' => 1]);
                    if (!$result) {
                        $m .= 'rfid:' . $v . ApiException::UPDATE_BOOK_YC_FAIL;
                    }
                    $result = $this->errorBookWork($v, $code, $uid, ErrBook::STATUS_1, '管理员拿走未知状态书籍');
                    if (!$result) {
                        $m .= '未知状态书籍rfid:' . $v . ApiException::ERRBOOK_WORK_FAIL;
                    }
                    break;
            }

        }

        return $m;

    }




    /**读者还书
     * @param $rfid
     * @param $uid
     * @param $code     //门码
     * @param $number   //门内书的数量
     */
    public function  returnBookByReader($rfid,$uid,$code,$number){
        $m='';
        $bookIds=[];
        //用户
        foreach ($rfid as $k => $v) {
            //判断书籍
            $tag = $this->tagInfoService->getTagStatusByRfid($v);
            //不存在的书
            if (!$tag || $tag->Barcode == null) {
                $result = $this->errorBookWork($v, $code, $uid, ErrBook::STATUS_1, '读者放入空标签');
                if (!$result) {
                    $m .= '空标签rfid:' . $v . ApiException::ERRBOOK_WORK_FAIL;
                }
                continue;
            }
            $item = $this->itemService->getItemByBarCode($tag->Barcode);

            //不存在的书
            if (!$item ) {
                $result = $this->errorBookWork($v, $code, $uid, ErrBook::STATUS_1, '读者放入空标签');
                if (!$result) {
                    $m .= '空标签rfid:' . $v . ApiException::ERRBOOK_WORK_FAIL;
                }
                continue;
            }

            //更新书机器关系
            $result=$this->bookInDoorService->returnUpdateRelation($code,$v);
            if(!$result){
                $m .= 'rfid:' . $v . ApiException::UPDATE_BOOK_IN_DOOR_FAIL;
            }

            //异常书 b_status=1
            if ($item->bookstatus) {
                $result = $this->errorBookWork($v, $code, $uid, ErrBook::STATUS_1, '读者放入异常书籍');
                if (!$result) {
                    $m .= '异常书籍rfid:' . $v . ApiException::ERRBOOK_WORK_FAIL;
                }
                continue;
            }

            switch ($item->LTStatus) {
                case '1':
                    //更新为异常书 1
                    $result = $item->update(['bookstatus' => 1]);
                    if (!$result) {
                        $m .= 'rfid:' . $v . ApiException::UPDATE_BOOK_YC_FAIL;
                    }
                    $result = $this->errorBookWork($v, $code, $uid, ErrBook::STATUS_1, '读者放入仓库书籍');
                    if (!$result) {
                        $m .= '仓库书籍rfid:' . $v . ApiException::ERRBOOK_WORK_FAIL;
                    }
                    break;
                case '2':
                    //更新为上架状态  3
                    $result = $item->update(['LTStatus' => 3]);
                    if (!$result) {
                        $m .= 'rfid:' . $v . ApiException::UPDATE_BOOK_SJ_FAIL;
                    }
                    break;
                case '3':

                    break;
                case '4':
                    //还书操作
                    $result = $this->returnBook($item->SerialNo, $code,$number);
                    if (!$result) {
                        $m .= 'rfid:' . $v . ApiException::BACK_BOOK_FAIL;
                    }
                    //更新为上架状态  3
                    $result = $item->update(['LTStatus' => 3]);
                    if (!$result) {
                        $m .= 'rfid:' . $v . ApiException::UPDATE_BOOK_SJ_FAIL;
                    }
                    break;
                case '5':
                    //更新为上架状态  3
                    $result = $item->update(['LTStatus' => 3]);
                    if (!$result) {
                        $m .= 'rfid:' . $v . ApiException::UPDATE_BOOK_SJ_FAIL;
                    }
                    break;
                case '6':
                    //更新为异常书 1
                    $result = $item->update(['bookstatus' => 1]);
                    if (!$result) {
                        $m .= 'rfid:' . $v . ApiException::UPDATE_BOOK_YC_FAIL;
                    }
                    $result = $this->errorBookWork($v, $code, $uid, ErrBook::STATUS_1, '读者放入外售书籍');
                    if (!$result) {
                        $m .= '外售书籍rfid:' . $v . ApiException::ERRBOOK_WORK_FAIL;
                    }
                    break;
                default:
                    //更新为异常书 1
                    $result = $item->update(['bookstatus' => 1]);
                    if (!$result) {
                        $m .= 'rfid:' . $v . ApiException::UPDATE_BOOK_YC_FAIL;
                    }
                    $result = $this->errorBookWork($v, $code, $uid, ErrBook::STATUS_1, '读者放入未知状态书籍');
                    if (!$result) {
                        $m .= '未知状态书籍rfid:' . $v . ApiException::ERRBOOK_WORK_FAIL;
                    }
                    break;
            }

        }

        return $m;
    }





     /*管理员上架图书
     * @param $rfid
     * @param $uid
     * @param $code     //门码
     */
    public function  returnBookByAdmin($rfid,$uid,$code,$number){
        $m='';
        //管理员
        foreach ($rfid as $k => $v) {
            //判断书籍
            $tag = $this->tagInfoService->getTagStatusByRfid($v);
            //不存在的书
            if (!$tag || $tag->Barcode == null) {
                $result = $this->errorBookWork($v, $code, $uid, ErrBook::STATUS_1, '管理员放入空标签');
                if (!$result) {
                    $m .= '空标签rfid:' . $v . ApiException::ERRBOOK_WORK_FAIL;
                }
                continue;
            }

            $item = $this->itemService->getItemByBarCode($tag->Barcode);

            //不存在的书
            if (!$item) {
                $result = $this->errorBookWork($v, $code, $uid, ErrBook::STATUS_1, '管理员放入空标签');
                if (!$result) {
                    $m .= '空标签rfid:' . $v . ApiException::ERRBOOK_WORK_FAIL;
                }
                continue;
            }

            //更新书机器关系
            $result=$this->bookInDoorService->returnUpdateRelation($code,$v);
            if(!$result){
                $m .= 'rfid:' . $v . ApiException::UPDATE_BOOK_IN_DOOR_FAIL;
            }

            //异常书 b_status=1
            if ($item->bookstatus) {
                $result = $this->errorBookWork($v, $code, $uid, ErrBook::STATUS_1, '管理员放入异常书籍');
                if (!$result) {
                    $m .= '异常书籍rfid:' . $v . ApiException::ERRBOOK_WORK_FAIL;
                }
                continue;
            }

            switch ($item->LTStatus) {
                case '1':
                    //更新为异常书 1
                    $result = $item->update(['bookstatus' => 1]);
                    if (!$result) {
                        $m .= 'rfid:' . $v . ApiException::UPDATE_BOOK_YC_FAIL;
                    }
                    $result = $this->errorBookWork($v, $code, $uid, ErrBook::STATUS_1, '管理员放入仓库书籍');
                    if (!$result) {
                        $m .= '仓库书籍rfid:' . $v . ApiException::ERRBOOK_WORK_FAIL;
                    }
                    break;
                case '2':
                    //更新为上架状态  3
                    $result = $item->update(['LTStatus' => 3]);
                    if (!$result) {
                        $m .= 'rfid:' . $v . ApiException::UPDATE_BOOK_SJ_FAIL;
                    }
                    break;
                case '3':
                    break;
                case '4':
                    //还书操作
                    $result = $this->returnBook($item->SerialNo, $code,$number);
                    if (!$result) {
                        $m .= 'rfid:' . $v . ApiException::BACK_BOOK_FAIL;
                    }
                    //更新为上架状态  3
                    $result = $item->update(['LTStatus' => 3]);
                    if (!$result) {
                        $m .= 'rfid:' . $v . ApiException::UPDATE_BOOK_SJ_FAIL;
                    }
                    break;
                case '5':
                    //更新为上架状态  3
                    $result = $item->update(['LTStatus' => 3]);
                    if (!$result) {
                        $m .= 'rfid:' . $v . ApiException::UPDATE_BOOK_SJ_FAIL;
                    }
                    break;
                case '6':
                    //更新为异常书 1
                    $result = $item->update(['bookstatus' => 1]);
                    if (!$result) {
                        $m .= 'rfid:' . $v . ApiException::UPDATE_BOOK_YC_FAIL;
                    }
                    $result = $this->errorBookWork($v, $code, $uid, ErrBook::STATUS_1, '管理员放入外售书籍');
                    if (!$result) {
                        $m .= '外售书籍rfid:' . $v . ApiException::ERRBOOK_WORK_FAIL;
                    }
                    break;
                default:
                    //更新为异常书 1
                    $result = $item->update(['bookstatus' => 1]);
                    if (!$result) {
                        $m .= 'rfid:' . $v . ApiException::UPDATE_BOOK_YC_FAIL;
                    }
                    $result = $this->errorBookWork($v, $code, $uid, ErrBook::STATUS_1, '管理员放入未知状态书籍');
                    if (!$result) {
                        $m .= '未知状态书籍rfid:' . $v . ApiException::ERRBOOK_WORK_FAIL;
                    }
                    break;
            }

        }
        return $m;

    }



    //异常书处理
    public function errorBookWork($bookUid,$doorid,$readerid,$status,$remark){
        DB::beginTransaction();
        try {
            //添加异常书
            $this->errBookService->updateErrBook($bookUid,$doorid,$readerid,$status);
            //添加异常书日志
            $this->errBookLogService->createErrBookLog($bookUid,$doorid,$readerid,$status,$remark);
            DB::commit();
       }catch (\Exception $e) {
            DB::rollback();
            return false;
        }
        return true;
    }


    //还书操作
    public function returnBook($bookid,$doorid,$number){
        DB::beginTransaction();
        try {
            //添加关系
            $this->lendLisService->delListByBookid($bookid);
            //添加关系日志
            $this->lendHisService->updateLendHistByBookId($bookid,$doorid,Lendhist::STATUS_1);
            DB::commit();
        }catch (\Exception $e) {

            DB::rollback();
            return false;
        }
        //回调APP接口
        $data['book_id'] = $bookid;
        $data['cabinet'] = $number;
        $this->appRequest('https://api.lexiangyueshu.com/callback/return',$data);

        return true;
    }

    //借书操作
    public function borrowBook($bookid,$doorid,$readerid,$number){
        DB::beginTransaction();
        try {
            $this->itemService->updateLTStatuesByBookId($bookid);
            //添加关系
            $this->lendLisService->insertLendlist($bookid,$readerid,$doorid);
            //添加关系日志
            $this->lendHisService->insertLendHist($bookid,$readerid,$doorid);
            DB::commit();
        }catch (\Exception $e) {
            DB::rollback();
            return false;
        }
        //回调APP接口
        $data['uid'] = $readerid;
        $data['book_id'] = $bookid;
        $data['cabinet'] = $number;
        $this->appRequest('https://api.lexiangyueshu.com/callback/borrow',$data);
        return true;
    }


    //app请求
    public function appRequest($url,$data){
        $ci = curl_init();
        curl_setopt($ci, CURLOPT_TIMEOUT, 30);
        curl_setopt($ci, CURLOPT_RETURNTRANSFER, true);
        $params = http_build_query($data);
        if (!empty($params)) {
            curl_setopt($ci, CURLOPT_POST, true);
            curl_setopt($ci, CURLOPT_POSTFIELDS, $params);
        }
        curl_setopt($ci, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ci, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($ci, CURLOPT_URL, $url);
        curl_exec($ci);
        curl_close($ci);
    }

}